package com.sangfor.provider.controller;

import com.sangfor.provider.entity.Depart;
import com.sangfor.provider.service.DepartService;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.List;
import java.util.Map;

/**
 * @author 朱勇军
 * @date 2020/7/25
 */
@RestController
@RequestMapping("/provider/depart")
public class DepartController {

    @Resource
    private DepartService departService;

    @Resource
    private DiscoveryClient client;

    @PostMapping("/create")
    public Depart create(@RequestBody Depart depart){
        return departService.createDepart(depart);
    }
    @GetMapping("/get/{id}")
    public Depart getById(@PathVariable Integer id){
        return departService.getDepart(id);
    }
    @DeleteMapping("/del/{id}")
    public boolean del(@PathVariable Integer id){
        return departService.removeDepartById(id);
    }
    @GetMapping("/list")
    public List<Depart> list(){
        return departService.listAllDepart();
    }

    @GetMapping("/discovery")
    public Object discovery(){
        List<String> services = client.getServices();
        for (String name: services){
            List<ServiceInstance> instances = client.getInstances(name);
            for (ServiceInstance s: instances){
                String host = s.getHost();
                int port = s.getPort();
                Map<String, String> metadata = s.getMetadata();
                System.out.println("metadata:" + metadata);
                System.out.println(host + ":" + port);
            }
        }
        return services;
    }
}
